<?php

use think\migration\Migrator;
use think\migration\db\Column;

class CreateRbacTable extends Migrator
{
    const ITEM_TABLE = 'permission';
    const ITEM_CHILD_TABLE = 'role_permission';
    const ITEM_ASSIGNMENT_TABLE = 'assignment';
    const RELATE_USER_TABLE = 'user';

    public function change()
    {
        //创建权限表
        // create the table
        $table  =  $this->table(addTablePrefix(self::ITEM_TABLE),[
            'engine'=>'InnoDB',
            'comment' => '权限角色表',
            'signed' => false
        ]);
        $table
            ->addColumn('name', 'string',array('limit'  =>  64,'default'=>'','comment'=>'权限名称或角色名称'))
            ->addColumn('type', 'integer',array('signed' => false, 'default'=>2,'comment'=>'1为角色 2为权限'))
            ->addColumn('rule', 'integer',array('signed' => false, 'default'=>1,'comment'=>'规则'))
            ->addColumn('desc', 'string',array('limit' => 255, 'default'=>'','comment'=>'描述'))
            ->addColumn('create_time', 'integer',array('signed' => false, 'default'=>0,'comment'=>'创建时间'))
            ->addColumn('update_time', 'integer',array('signed' => false, 'default'=>0,'comment'=>'修改时间'))
            ->addIndex(array('name'), array('unique'  =>  true))
            ->create();

        //创建权限关联表
        // create the table
        $table  =  $this->table(addTablePrefix(self::ITEM_CHILD_TABLE),[
            'engine'=>'InnoDB',
            'comment' => '权限角色关联表',
            'signed' => false
        ]);
        $table
            ->addColumn('permission_id', 'integer',array('signed' => false, 'default'=>0,'comment'=>'权限id'))
            ->addColumn('role_id', 'integer',array('signed' => false, 'default'=>0,'comment'=>'角色id'))
            //->addColumn('create_time', 'integer',array('signed' => false, 'default'=>0,'comment'=>'创建时间'))
            ->addForeignKey('permission_id', addTablePrefix(self::ITEM_TABLE), 'id', ['delete'=> 'CASCADE', 'update'=> 'NO_ACTION'])
            ->addForeignKey('role_id', addTablePrefix(self::ITEM_TABLE), 'id', ['delete'=> 'CASCADE', 'update'=> 'NO_ACTION'])
            ->create();

        //创建指派表
        // create the table
        $table  =  $this->table(addTablePrefix(self::ITEM_ASSIGNMENT_TABLE),[
            'engine'=>'InnoDB',
            'comment' => '角色指派表',
            'signed' => false
        ]);
        $table
            ->addColumn('user_id', 'integer',array('signed' => false, 'default'=>0,'comment'=>'用户'))
            ->addColumn('permission_id', 'integer',array('signed' => false, 'default'=>0,'comment'=>'角色'))
            //->addColumn('create_time', 'integer',array('signed' => false, 'default'=>0,'comment'=>'创建时间'))
            ->addForeignKey('user_id', addTablePrefix(self::RELATE_USER_TABLE), 'id', ['delete'=> 'CASCADE', 'update'=> 'NO_ACTION'])
            ->addForeignKey('permission_id', addTablePrefix(self::ITEM_TABLE), 'id', ['delete'=> 'CASCADE', 'update'=> 'NO_ACTION'])
            ->create();
    }
}
